package models;

import java.util.Collections;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;

import entities.InLink;

public class InLinkModel {
	private Objectify ofy;
	
	private Cache cache = null;
	
	private String prefix = "inlink_";
	
	private static InLinkModel instance = null;
	
	private int limit = 50;
	
	public static InLinkModel getInstance() {
		if (instance == null) {
			instance = new InLinkModel();
		}
		
		return instance;
	}
	
	private InLinkModel() {
		try {
			ObjectifyService.register(InLink.class);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		/*try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           //e.printStackTrace();
        }*/
		
        ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}
	
	public void insert(InLink inlink) {
		if (cache != null) {
			cache.put(prefix + inlink.getDomain(), inlink);
		}
		ofy.async().put(inlink);
	}
	
	public InLink get(String domain) {
		InLink inlink = new InLink();
		if (cache != null && cache.containsKey(prefix + domain)) {
			inlink = (InLink) cache.get(prefix + domain);
		} else {
			try {
				inlink = ofy.get(new Key<InLink>(InLink.class, domain));
				if (cache != null) {
					cache.put(prefix + domain, inlink);
				}
			} catch (Exception e) {
				inlink = null;
			}
		}
		return inlink;
	}
	
	public void insert(String domain, List<String> links) {
		InLink inlink = new InLink();
		for (int i = 0; i < links.size(); i++) {
			String name = links.get(i).replaceAll("(http|https)+://(www.)*", "");
			inlink = get(name);
			if (inlink == null) {
				inlink = new InLink();
				inlink.setDomain(name);
			}
			
			List<String> domains = inlink.getDomains(); 
			if (!domains.contains(domain) && domains.size() <= limit) {
				domains.add(domain);
				inlink.setDomains(domains);
				if (cache != null) {
					cache.put(prefix + inlink.getDomain(), inlink);
				}
				insert(inlink);
			}
		}
	}
	
	public void delete(InLink inlink) {
		if (cache != null && cache.containsKey(prefix + inlink.getDomain())) {
			cache.remove(prefix + inlink.getDomain());
		}
		ofy.delete(inlink);
	}
}
